<template>
  <div class="createArticleMain">
    <div class="banner" :style="articleCover"></div>

    <div style="margin-top: 380px;width: 80%;">
    <el-form :model="articleData" ref="formData" label-width="180px" label-position="right">
      <el-form-item label="标题：" prop="title" >
        <el-input v-model="articleData.title" placeholder="请输入标题" show-word-limit maxlength="50" />
      </el-form-item>
      <el-form-item label="摘要：" prop="summary">
        <el-input v-model="articleData.summary" placeholder="请输入摘要" show-word-limit maxlength="300" />
      </el-form-item>

      <el-form-item label="分类：" prop="checkedCategoryId">
        <el-select v-model="checkedCategoryId" placeholder="请选择">
          <el-option
              v-for="item in categoryList"
              :key="item.categoryId"
              :label="item.categoryName"
              :value="item.categoryId">
          </el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="标签：" prop="checkedLabelId">
        <el-select v-model="checkedLabelId" placeholder="请选择">
          <el-option
              v-for="item in labelList"
              :key="item.labelId"
              :label="item.labelName"
              :value="item.labelId">
          </el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="封面图：" prop="cover" >
        <el-upload class="avatar-uploader" action="" :show-file-list="false" :http-request="uploadArticleCover">
          <img v-if="articleData.cover" :src="articleData.cover" style="width: 100px;height: 100px;display: block">
          <i v-else class="el-icon-plus avatar-uploader-icon"></i>
        </el-upload>
        <el-button type="primary" size="small" @click="getDefaultImg"> 使用默认图片 </el-button>
      </el-form-item>

      <el-form-item label="文章类型：" prop="articleType">
        <el-radio-group v-model="articleData.articleType">
          <el-radio :label = "1" border>原创</el-radio>
          <el-radio :label = "2" border>转载</el-radio>
        </el-radio-group>
      </el-form-item>

      <el-form-item label="转载链接：" prop="curationLink" v-if = "articleData.articleType === 2">
        <el-input v-model="articleData.curationLink"
                  placeholder="请输入转载链接"
                  show-word-limit maxlength="200" />
      </el-form-item>

      <el-form-item label="可见范围：" prop="publicType">
        <el-radio-group v-model="articleData.publicType">
          <el-radio :label = "1" border>仅自己可见</el-radio>
          <el-radio :label = "2" border>组织内成员可见</el-radio>
          <el-radio :label = "3" border>所有人可见</el-radio>
        </el-radio-group>
      </el-form-item>

      <el-form-item label="允许评论：" prop="allowComment">
        <el-radio-group v-model="articleData.allowComment">
          <el-radio :label="1" border>允许</el-radio>
          <el-radio :label="0" border>不允许</el-radio>
        </el-radio-group>
      </el-form-item>

      <el-form-item label="定时发布：" prop="timedRelease">
        <el-radio-group v-model="articleData.timedRelease">
          <el-radio :label = "1" border>是</el-radio>
          <el-radio :label = "0" border>否</el-radio>
        </el-radio-group>
      </el-form-item>

      <el-form-item label="定时发布时间：" prop="cronReleaseTime" v-if="articleData.timedRelease === 1">
        <el-date-picker v-model="articleData.cronReleaseTime" type="datetime" placeholder="选择发布时间">
        </el-date-picker>
      </el-form-item>

      <el-form-item label="内容：" prop="htmlContent" >
        <mavon-editor id="md" ref="md" v-model="articleData.mdContent" @change="getMdHtml"
                      @imgAdd="uploadContentImg"
                      @imgDel="delContentImg" />
      </el-form-item>
      <el-row style="margin-bottom: 10px;float: right" >
        <el-button type="warning" plain @click="back" :loading="loading" >返回</el-button>
        <el-button type="success" @click="editArticle" :loading="loading">提交</el-button>
      </el-row>
    </el-form>
    </div>

    <el-dialog :visible.sync="dialogVisible" width="20%">
      <span>
        <el-result icon="success" title="编辑成功！正在审核中">
          <template slot="extra">
            <el-button type="info" size="medium" @click="manageArticle">管理文章</el-button>
            <el-button type="primary" size="medium" @click="createAgain">再写一篇</el-button>
          </template>
        </el-result>
      </span>
    </el-dialog>

  </div>
</template>
<script >
import { mavonEditor } from 'mavon-editor';
import 'mavon-editor/dist/css/index.css';
import { uploadFile } from "../../api/file";
import { categoryList, getLabelByCategoryId,  articleInfo, updateArticle } from '../../api/article';
import { getBaseSystemConfig } from '../../api/system';
import { ARTICLE_DEFAULT_COVER } from '../../utils/constants';
import { format } from "../../utils/date";
import { getUserId } from '../../utils/cookieUtil';

export default {
  components:{
    mavonEditor, // 引入markdown编辑器
  },

  data() {
    return {
      articleData: {
        cover: '',
        articleType: '',
        curationLink: '',
        publicType: '',
        allowDownload: '',
        allowComment: '',
        timedRelease: '',
        cronReleaseTime: '',
        autoPublish: '',
        mdContent: '',
        summary: ''
      },
      checkedCategoryId: '',
      categoryList: [],
      labelList: [],
      checkedLabelId: '',
      loading: false,
      dialogVisible: false,
      valid: true,
      articleId: this.$route.params.articleId
    }
  },

  created() {
    this.getCategoryList();
    this.fetchArticleInfo();
  },

  watch: {
    checkedCategoryId (newId, oldId) {
      this.checkedLabelId  = '';
      if (newId) {
        this.getLabelList(newId);
      }
    }
  },

  methods: {
    // 获取文章信息
    fetchArticleInfo() {
      articleInfo(this.articleId).then(res => {
        if (res.code === 200) {
          this.articleData = res.data;
          this.checkedCategoryId = res.data.categoryId;
          this.checkedLabelId = res.data.labelId;
        } else {
          this.$message.error(res.message);
        }
      })
    },

    // 获取分类列表
    getCategoryList() {
      categoryList().then(res => {
        if (res.code === 200) {
          this.categoryList = res.data;
        } else {
          this.$message.error(res.message)
        }
      })
    },

    // 根据分类ID获取标签信息列表
    getLabelList(categoryId) {
      getLabelByCategoryId(categoryId).then(res => {
        if (res.code === 200) {
          this.labelList = res.data;
        }
      })
    },

    // 上传文章封面图
    uploadArticleCover(file) {
      const data = new FormData();
      data.append('file', file.file);
      data.append('type', 'article_img');
      uploadFile(data).then(response => {
        if(response.code === 200) {
          console.log(response.data)
          this.articleData.cover = response.data;
        } else {
          this.$notify.error({
            title: '错误',
            message: response.message,
            duration: 1500
          });
        }
      }).catch(err => {
        this.$message({
          type: 'error',
          message: '上传失败'
        })
      })
    },

    // 使用默认图片
    getDefaultImg() {
      getBaseSystemConfig().then(res => {
        if (res.code === 200) {
          this.articleData.cover = res.data.articleDefaultCover;
          if (!this.articleData.cover) {
            this.articleData.cover = ARTICLE_DEFAULT_COVER;
          }
          this.getCategoryList();
        } else {
          this.$message.error(res.message)
        }
      })
    },

    getMdHtml(mdContent, htmlContent) {
      this.articleData.mdContent = mdContent;
      this.articleData.htmlContent = htmlContent;
    },

    uploadContentImg(pos,file) {
      const fd = new FormData();
      fd.append('file',file);
      fd.append('type', 'article_img');
      uploadFile(fd).then(resp => {
        if(resp.code === 200){
          this.$refs.md.$img2Url(pos, resp.data);
        }
      })
    },

    delContentImg(urlAndFileArr) {
      const fileUrl = urlAndFileArr[0];
      const file = urlAndFileArr[1];
      console.log('删除图片',fileUrl,file);
      //deleteFile(fileUrl);
    },

    // 发布文章
    editArticle() {
      this.loading = true;
      this.beforeUpdateArticle();
      if (!this.valid) {
        this.valid = true;
        this.loading = false;
        return;
      }
      this.articleData.categoryId = this.checkedCategoryId;
      this.articleData.labelId = this.checkedLabelId;
      this.articleData.articleId = this.articleId;
      if (this.articleData.cronReleaseTime) {
        this.articleData.cronReleaseTime = format(this.articleData.cronReleaseTime);
      }

      // 请求编辑文章的接口
      updateArticle(this.articleData).then(res => {
        if (res.code === 200) {
          this.dialogVisible = true;
        } else {
          this.$message.error(res.message);
          this.loading = false;
        }
      }).catch(err => {
        this.loading = false;
      })
    },

    // 再写一篇
    createAgain() {
      this.$router.push('/create')
    },

    // 管理文章
    manageArticle() {
      this.$router.replace('/user/' + getUserId());
    },

    // 回到上一页
    back() {
      this.$router.go(-1);
    },

    // 发布文章前检查必填项
    beforeUpdateArticle() {
      if (!this.articleData.title) {
        this.$message.error('请输入标题');
        this.valid = false;
        return
      }

      if (!this.articleData.summary) {
        this.$message.error('请输入摘要');
        this.valid = false;
        return
      }

      if (!this.checkedCategoryId) {
        this.$message.error('请选择分类');
        this.valid = false;
        return
      }

      if (!this.checkedLabelId) {
        this.$message.error('请选择标签');
        this.valid = false;
        return
      }

      if (!this.articleData.cover) {
        this.$message.error('请上传封面图');
        this.valid = false;
        return
      }

      if (this.articleData.articleType !== 1 && this.articleData.articleType !== 2) {
        this.$message.error('请选择文章类型');
        this.valid = false;
        return
      }

      if (this.articleData.articleType === 2 && !this.articleData.curationLink) {
        this.$message.error('请输入转载链接');
        this.valid = false;
        return
      }

      if (!this.articleData.publicType) {
        this.$message.error('请选择可见范围');
        this.valid = false;
        return
      }

      if (this.articleData.allowComment !== 0 && this.articleData.allowComment !== 1) {
        this.$message.error('请选择是否允许评论');
        this.valid = false;
        return
      }

      if (this.articleData.allowDownload !== 0 && this.articleData.allowDownload !== 1) {
        this.$message.error('请选择是否允许下载');
        this.valid = false;
        return
      }

      if (this.articleData.timedRelease !== 1 && this.articleData.timedRelease !== 0) {
        this.$message.error('请选择是否定时发布');
        this.valid = false;
        return
      }

      if (this.articleData.timedRelease && !this.articleData.cronReleaseTime) {
        this.$message.error('请选择定时发布时间');
        this.valid = false;
        return
      }

      if (this.articleData.autoPublish !== 0 && this.articleData.autoPublish !== 1) {
        this.$message.error('请选择是否审批通过后自动发布');
        this.valid = false;
        return
      }

      if (!this.articleData.htmlContent) {
        this.$message.error('请输入文章内容');
        this.valid = false;
      }
    }

  },

  computed: {
    articleCover() {
      return (
          "background: url(" +
          'https://98k-hk666.oss-cn-shanghai.aliyuncs.com/iblog/img/234958-160502339805f5.jpg' +
          ") center center / cover no-repeat"
      );
    },

  }
}

</script>

<style>
.createArticleMain {
  width: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
}

.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 100px;
  height: 100px;
  line-height: 100px;
  text-align: center;
}
.avatar {
  width: 100px;
  height: 100px;
  display: block;
}

@media (min-width: 760px) {
  .article-list-wrapper {
    max-width: 1106px;
    margin: 370px auto 1rem auto;
  }
  .article-item-card:hover {
    transition: all 0.3s;
    box-shadow: 0 4px 12px 12px rgba(7, 17, 27, 0.15);
  }
  .article-item-card:not(:hover) {
    transition: all 0.3s;
  }
  .article-item-card:hover .on-hover {
    transition: all 0.6s;
    transform: scale(1.1);
  }
  .article-item-card:not(:hover) .on-hover {
    transition: all 0.6s;
  }
  .article-item-info {
    line-height: 1.7;
    padding: 15px 15px 12px 18px;
    font-size: 15px;
  }
}
@media (max-width: 759px) {
  .article-list-wrapper {
    margin-top: 230px;
    padding: 0 12px;
  }
  .article-item-info {
    line-height: 1.7;
    padding: 15px 15px 12px 18px;
  }
}
.article-item-card {
  border-radius: 8px !important;
  box-shadow: 0 4px 8px 6px rgba(7, 17, 27, 0.06);
}
.article-item-card a {
  transition: all 0.3s;
}
.article-item-cover {
  height: 220px;
  overflow: hidden;
}
.article-item-card a:hover {
  color: #8e8cd8;
}
.tag-wrapper a {
  color: #fff !important;
}
</style>